﻿using FakeXiecheng.API.Dtos;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using FakeXiecheng.API.Moldes;
using FakeXiecheng.API.Services;

namespace FakeXiecheng.API.Controllers
{
    [ApiController]
    [Route("auth")]
    public class AuthenticateController : ControllerBase
    {
        //注入依赖
        private readonly IConfiguration _configuration;
        private readonly UserManager<ApplicationUser> _userManager;//注册用户
        private readonly SignInManager<ApplicationUser> _signInManager;//服务依赖
        private readonly ITouristRouteRepository _touristRouteRepository;
        public AuthenticateController(IConfiguration configuration, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ITouristRouteRepository touristRouteRepository)
        {
            _configuration = configuration;
            _userManager = userManager;
            _signInManager = signInManager;
            _touristRouteRepository = touristRouteRepository;
        }
        [AllowAnonymous]
        [HttpGet("login")]
        public async Task<IActionResult> login([FromBody] LoginDto loginDto)
        {
            //1.验证用户名密码
            var loginResult = await _signInManager.PasswordSignInAsync
                (
                loginDto.Email,
                loginDto.Password,
                false,
                false
                );
            if(!loginResult.Succeeded)
            {
                return BadRequest();//用户名验证失败
            }
            var user = await _userManager.FindByNameAsync(loginDto.Email);
            //2.创建jwt header signiture
            var signingAlgorithm=SecurityAlgorithms.HmacSha256;
            //payload  Don't compare yourself with wild animals
            var claims = new List<Claim>//资源所有权--用户身份-角色等
            {
                //sub
                new Claim(JwtRegisteredClaimNames.Sub,user.Id),
                //new Claim(ClaimTypes.Role,"Admin")

            };
            var roleNames=await _userManager.GetRolesAsync(user);//角色列表
            //循环读取列表
            foreach(var roleName in roleNames)
            {
                var roleClaim=new Claim(ClaimTypes.Role,roleName);
                claims.Add(roleClaim);
            }
            //signiture
            var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
            var signingKey=new SymmetricSecurityKey(secretByte);
            var signingCredentials=new SigningCredentials(signingKey, signingAlgorithm);
            var token = new JwtSecurityToken(
                issuer: _configuration["Authentication:Issuer"],
                audience: _configuration["Authentication:Audience"],
                claims,
                notBefore:DateTime.UtcNow,
                expires: DateTime.UtcNow.AddDays(1),
                signingCredentials
                );
            var tokenStr=new JwtSecurityTokenHandler().WriteToken(token);
            //3. return 200 ok +jwt
            return Ok(tokenStr);
        }

        [AllowAnonymous]
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterDto registerDto)
        {
            //1.创建用户名创建用户对象
            var user = new ApplicationUser()
            {
                UserName = registerDto.Email,
                Email = registerDto.Email
            };
            //2.hash密码，保存用户
            var result=await _userManager.CreateAsync(user,registerDto.Password);
            if(!result.Succeeded)
            {
                return BadRequest();//返回失败
            }
            //3.初始化购物车
            var shoppingCart = new ShoppingCart()
            {
                Id = Guid.NewGuid(),
                UserId = user.Id
            };
            await _touristRouteRepository.CreateShoppingCart(shoppingCart);
            await _touristRouteRepository.SaveAsync();
            //4 return
            return Ok();
        }

        [HttpDelete("items/{itemId}")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> DeleteShoppingCartItem([FromRoute] int itemId)
        {
            // 1 获取lineitem数据
            var lineItem = await _touristRouteRepository
                .GetShoppingCartItemByItemId(itemId);
            if (lineItem == null)
            {
                return NotFound("购物车商品找不到");
            }

            _touristRouteRepository.DeleteShoppingCartItem(lineItem);
            await _touristRouteRepository.SaveAsync();

            return NoContent();
        }

    }
}
